package com.jinloes.webfit;

import com.jinloes.webfit.persistence.UserTest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;

@Controller
@RequestMapping("/user")
public class ProfileController {
	private static final Logger logger = LoggerFactory.getLogger(ProfileController.class);
	
	@Autowired
	private UserValidator userValidator;
	
	public void setUserValidator(UserValidator userValidator) {
		this.userValidator = userValidator;
	}
	
	@RequestMapping(value="/profile", method=RequestMethod.GET)
	public String profile(String test, Model model) {
		model.addAttribute("test", test);
		logger.info("Welcome to your profile!");
		return "profile";
	}
	
	@RequestMapping(value="/getUser", method=RequestMethod.GET)
	public @ResponseBody
    UserTest getUser() {
		return new UserTest();
	}
//	@RequestMapping(value="/getUser", method=RequestMethod.GET)
//	public ModelAndView getUser(){	
//		
//		return new ModelAndView("user","user",new UserTest() );
//		
//	}
	
	@RequestMapping(method=RequestMethod.GET, value="/register")
	public String registerUser(Model model) {
		model.addAttribute("user", new UserTest());
		return "register";
	}
	
	@RequestMapping(value="/create", method=RequestMethod.POST)
	public String addUser(@Valid UserTest user, BindingResult bindingResult, Model model) {
		
		logger.info("attempting to create profile");
		userValidator.validate(user, bindingResult);
		if(bindingResult.hasErrors()){
			logger.info("errors");
			return "register";
		}
		
//		try {
//			if(!image.isEmpty()) {
//				validateImage(image);
//			}
//			
//			saveImage("blah.jpg", image);
//			
//		}
//		catch(Exception e) {
//			bindingResult.reject(e.getMessage());
//			return "redirect://register";
//		}
		logger.info("username: " + user.getUsername());
		model.addAttribute("name", user.getUsername());
		return "redirect:/";
	}
	
//	private void validateImage(MultipartFile image) throws Exception {
//		if(!image.getContentType().equals("image/jpeg")) {
//			throw new Exception("Only JPG images accepted");
//		}
//	}
	
//	private void saveImage(String filename, MultipartFile image) throws Exception {
//		try {
//			File file = new File("/resources/" + filename);
//		}
//		catch(IOException e) {
//			throw new Exception("unable to save image", e);
//		}
//	}
}
